package cn.lili.controller.promotion;

import cn.hutool.core.collection.CollectionUtil;
import cn.lili.common.utils.ResultUtil;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.promotion.entity.dos.BoxMhgoods;
import cn.lili.modules.promotion.entity.dto.search.BoxMhGoodsSearchParams;
import cn.lili.modules.promotion.entity.vos.BoxMhgoodsVO;
import cn.lili.modules.promotion.service.BoxMhgoodsService;
import cn.lili.modules.system.constants.DictConstant;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 商品管理
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/promotion/box/mh")
public class BoxMhgoodsController {

    private BoxMhgoodsService boxMhgoodsService;
    private RedissonClient redisson;
    /**
     * 获取盲盒列表分页
     *
     * @param boxMhGoodsSearchParams 搜索条件
     * @return 盲盒列表
     */
    @GetMapping("/page")
    public ResultMessage<Object> pageBoxGoods(BoxMhGoodsSearchParams boxMhGoodsSearchParams) {
        return boxMhgoodsService.pageBoxGoods(boxMhGoodsSearchParams);
    }

    /**
     * 查询详情
     *
     * @return 详情
     */
    @GetMapping("/detail/{id}")
    public ResultMessage<Object> detail(@PathVariable String id) {
        return boxMhgoodsService.detail(id);
    }

    /**
     * 新增盲盒
     */
    @PostMapping("/add")
    public ResultMessage<Object> addBoxGoods(@RequestBody BoxMhgoodsVO boxMhgoodsVO) {
        return boxMhgoodsService.addBoxGoods(boxMhgoodsVO);
    }

    /**
     * 批量删除盲盒
     */
    @DeleteMapping("/delete")
    public ResultMessage<Object> deleteBoxGoods(@RequestParam String ids) {
        return ResultUtil.data(boxMhgoodsService.deleteBoxGoods(ids));
    }

    /**
     * 修改盲盒
     */
    @PutMapping("/update")
    public ResultMessage<Object> updateBoxGoods(@RequestBody BoxMhgoodsVO boxMhgoodsVO) {
        return boxMhgoodsService.updateBoxGoods(boxMhgoodsVO);
    }

    /**
     * 盲盒开关：正常来讲发布之后不能关闭。但考虑到异常情况给个入口可撤销
     * @param id 主键
     * @param publishType 1开，2关
     * @return 是否成功
     */
    @PutMapping("/change")
    public ResultMessage<Object> change(@RequestParam String id, @RequestParam Integer publishType) {
        return boxMhgoodsService.change(id, publishType);
    }

    /**
     * 盲盒下拉列表
     */
    @GetMapping("/select")
    public ResultMessage<Object> select(String name) {
        return boxMhgoodsService.select(name);
    }

    /**
     * 立即开奖
     */
    @PostMapping("/drawNow")
    public ResultMessage<Object> drawNow(@RequestParam String id) {
        return boxMhgoodsService.drawNow(id);
    }



    /**
     * 定时查询是否有需要开奖的盲盒(1分钟每次，并且是整点)
     */
    @Scheduled(cron = "0 0/1 * * * *")
    public void timedDrawNow() {
        RLock lock = null;
        try {
            lock = redisson.getLock("timedDrawNow");
            lock.lock(20, TimeUnit.SECONDS);

            List<BoxMhgoods> boxMhgoodsList = boxMhgoodsService.list(new LambdaQueryWrapper<BoxMhgoods>()
                    .eq(BoxMhgoods::getDeleteFlag, false)
                    .eq(BoxMhgoods::getMhStatus, DictConstant.MH_STATUS_03)
                    .eq(BoxMhgoods::getLotteryMethod, DictConstant.LOTTERY_METHOD_02)
                    .ge(BoxMhgoods::getLotteryDate, new Date())
            );
            if (CollectionUtil.isEmpty(boxMhgoodsList)) {
                return;
            }
            for (BoxMhgoods mhGoods : boxMhgoodsList) {
                boxMhgoodsService.drawNow(mhGoods.getId());
            }
        } catch (Exception e) {
            log.error("error == {}", e.getMessage());
            e.printStackTrace();
        } finally {
            if (lock != null) {
                lock.unlock();
                log.info("timedDrawNow强制释放锁");
            }
        }
    }
}
